<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Loader;
use think\Page;
use think\Validate;
use \app\admin\model\Activity as Activitys;
use \app\admin\model\ActivityCategory;
use \app\admin\model\ActivityComment;
use \app\admin\model\ActivityRegister;

class Activity extends Api
{
    protected $noNeedLogin = ['getActivityCategoryList', 'getActivityList', 'getActivityInfo', 'getCommentList'];
    protected $noNeedRight = '*';
    protected $user_id     = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
    }

    /**
     * @MethodName 活動分類
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getActivityCategoryList($value = '')
    {
        $model = new ActivityCategory;
        $list  = $model
            ->field('id,image,name,createtime')
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功', $list);
    }

    /**
     * @MethodName 獲取活動列表-报名记录
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getActivityBaomingList($value = '')
    {
        $center_id = input("center_id", 0);
        $ky        = input("ky", '');
        $where     = [];
        $where_or  = [];
        if ($center_id) {
            $where['s.center_id'] = $center_id;
        }
        $where['s.deletetime'] = null;
        $where['s.user_id']    = $this->user_id;

        $total = Db::name('activity_sign')->alias('s')
            ->where($where)
            ->count();

        $page = new Page($total, 10);
        $list = Db::name('activity_sign')->alias('s')
            ->join('activity a', 'a.id=s.activity_id')

            ->where($where)
            ->field('a.*')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('s.id desc')
            ->select();

        foreach ($list as $key => &$value) {
            $value['collection_num'] = db('collection')
                ->where(['type' => '5', 'relation_id' => $value['id']])
                ->count();
        }

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取活動列表
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getActivityList($value = '')
    {
        $cat_id    = input("cat_id", 0);
        $cat_id2    = input("cat_id2", 0);
        $is_yigong = input("is_yigong", 0);
        $ky        = input("ky", '');
        $keyword   = input("keyword", '');
        $where     = [];
        $where_or  = [];
        if ($cat_id) {
            //$where['cat_id'] = $cat_id;
            $where['area_one_id'] = $cat_id;

        }
          if ($cat_id2) {
            $where['cat_id'] = $cat_id2;
           

        }
        $where['deletetime'] = null;
        if ($ky) {
            $arr     = cnChangeStr($ky);
            $where_1 = [];
            if ($arr['cn_f'] == $arr['cn']) {
                $where_1['title'] = ['like', "%$ky%"];
            } else {
                $where_1['title']  = ['like', "%" . $arr['cn_f'] . "%"];
                $where_or['title'] = ['like', "%" . $arr['cn'] . "%"];
            }

            $subQuery = Db::name('activity')
                ->field('id,images,title,content,createtime,cat_id,deletetime,weigh,start_date,end_date,start_time,end_time')
                ->where($where_1)
                ->whereOr($where_or)
                ->where('is_yigong', $is_yigong)
                ->buildSql();
            $model = Db::table($subQuery . ' a');
            $total = $model
                ->where($where)
                ->count();
            $page = new Page($total, 10);
            $list = Db::table($subQuery . ' b')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('id desc')
                ->select();

        } else {

            $model = Db::name('activity');

            if (! empty($keyword)) {
                $where['title'] = ['like', "%$keyword%"];
            }
            $where['is_yigong'] = ['=', $is_yigong];
            $total              = $model
                ->where($where)
                ->count();

            $page = new Page($total, 10);
            $list = $model
                ->field('id,images,title,content,createtime,start_date,end_date,start_time,end_time,cat_id,area_one_id')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('id desc')
                ->select();

        }

        foreach ($list as $key => &$value) {
            $value['collection_num'] = db('collection')
                ->where(['type' => '5', 'relation_id' => $value['id']])
                ->count();
                                   //报名时间
            $value['status'] = 10; //报名中
            if ($value['end_time'] < time()) {
                $value['status'] = 20; //报名结束
            }
            if ($value['end_date'] < time()) {
                $value['status'] = 30; //活动结束
            }
            //报名人数
            $value['baoming_num'] = Db::name('child_q_data')->where('center_id', $value['id'])->count();
            //報名最新五人
            $ids            = Db::name('child_q_data')
            ->where('center_id', $value['id'])->limit(5)->order('id desc')->select();
            $ids            = array_column($ids, 'uid');
            $value['users'] = Db::name('user')->field('avatar')->where('id', 'in', $ids)->limit(5)->select();
        }

        unset($value);
        if ($this->user_id) {
            // 存儲用戶瀏覽記錄
            setArticleHistory($this->user_id, 4, 0);
        }

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取活動詳情
     * @Author     Allen
     * @DateTime   2021-10-04T15:42:20+0800
     * @return     [type]
     */
    public function getActivityInfo()
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $model   = new Activitys;
        $armodel = new ActivityRegister;
        $info    = $model
            ->field('*')
            ->where(['id' => $rq_data['id']])
            ->find();

        $model->where(['id' => $rq_data['id']])->setInc('click');

        if ($info) {

            $info['collection_num'] = db('collection')
                ->where(['type' => '5', 'relation_id' => $info['id']])
                ->count();

            $info['collection_status'] = db('collection')
                ->where(['type' => '5', 'relation_id' => $info['id'], 'user_id' => $this->user_id])
                ->count();

            $info['register_status'] = $armodel
                ->where(['activity_id' => $info['id'], 'user_id' => $this->user_id])
                ->count();

            $info['now_signup_num'] = $armodel
                ->where(['activity_id' => $info['id']])
                ->count();

            if ($this->user_id) {
                // 存儲用戶瀏覽記錄
                setArticleHistory($this->user_id, 4, $info['id']);
            }
            if ($info['qid'] > 0) {
                $q_info           = db('child_q_format')->where('qid', '=', $info['qid'])->field('available')->find();
                $info['q_status'] = $q_info['available'];
            }

        }

        $this->success('請求成功', $info ? $info : []);
    }

    /**
     * @MethodName 活動操作收藏
     * @Author     Allen
     * @DateTime   2021-10-04T16:12:36+0800
     * @param      string
     */
    public function setActivityCollection($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Activitys;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }
        $collection_status = db('collection')
            ->where(['type' => '5', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
            ->count();

        if ($collection_status) {
            $status = db('collection')
                ->where(['type' => '5', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
                ->delete();
        } else {
            $insert_arr                = [];
            $insert_arr['user_id']     = $this->user_id;
            $insert_arr['type']        = '5';
            $insert_arr['relation_id'] = $rq_data['id'];
            $insert_arr['createtime']  = time();
            $status                    = db('collection')->insert($insert_arr);
        }
        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    /**
     * @MethodName 發佈評論
     * @Author     Allen
     * @DateTime   2021-10-04T17:06:59+0800
     * @param      string
     * @return     [type]
     */
    public function publishComment($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('activity_comment')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Activitys;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }

        $acmodel                   = new ActivityComment;
        $insert_arr                = [];
        $insert_arr['activity_id'] = $info['id'];
        $insert_arr['user_id']     = $this->user_id;
        $insert_arr['content']     = $rq_data['content'];
        $insert_arr['createtime']  = time();
        $status                    = $acmodel->insert($insert_arr);

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }
    /**
     * @MethodName 報名
     * @Author     Allen
     * @DateTime   2021-10-04T17:06:59+0800
     * @param      string
     * @return     [type]
     */
    public function baoming($value = '')
    {
        $rq_data = $this->request->param();

        $model = new Activitys;
        $info  = $model
            ->field('*')
            ->where(['id' => $rq_data['id']])
            ->find();
        if (! $info) {
            $this->error('操作失敗');
        }

        //是否義工

        $volunteer = Db::name('volunteer')->where('affiliated_center_id', $info['area_one_id'])
            ->where('user_id', $this->user_id)->find();
        if (! $volunteer) {
            $this->error('您先申請義工');
        }

        if ($info['start_time'] > time()) {
            $this->error('活動尚未開始報名');
        }
        if ($info['end_time'] < time()) {
            $this->error('活動報名結束');
        }
        if ($info['is_open'] == 0) {
            $this->error('活動尚未開始報名');
        }

        //$model = new ActivitySign;
        $sign = Db::name('activity_sign')

            ->where(['activity_id' => $rq_data['id']])
            ->where(['user_id' => $this->user_id])
            ->find();

        if ($sign) {
            $this->error('已經報名');
        }

        $insert_arr                = [];
        $insert_arr['activity_id'] = $info['id'];
        $insert_arr['title'] = $info['title'];
        $insert_arr['vo_id']       = $volunteer['id'];
        $insert_arr['user_id']     = $this->user_id;
        $insert_arr['center_id']   = $info['area_one_id'];
        $insert_arr['hours']       = $info['workinghours'];
        $insert_arr['create_time']  = time();
        $status                    = Db::name('activity_sign')->insert($insert_arr);

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }
    /**
     * @MethodName 簽到
     * @Author     Allen
     * @DateTime   2021-10-04T17:06:59+0800
     * @param      string
     * @return     [type]
     */
    public function sign($value = '')
    {
        $rq_data = $this->request->param();

        $model = new Activitys;
        $info  = $model
            ->field('*')
            ->where(['id' => $rq_data['id']])
            ->find();
        if (! $info) {
            $this->error('操作失敗');
        }

        //是否義工

        $volunteer = Db::name('volunteer')->where('affiliated_center_id', $info['area_one_id'])
            ->where('user_id', $this->user_id)->find();
        if (! $volunteer) {
            $this->error('您先申請義工');
        }

        //$model = new ActivitySign;
        $sign = Db::name('activity_sign')

            ->where(['activity_id' => $rq_data['id']])
            ->where(['user_id' => $this->user_id])
            ->find();

        if (! $sign) {
            $this->error('請先報名活動');
        }
        if ($sign['sign_time'] > 0) {
            $this->error('您已簽到');
        }

        $insert_arr = [];

        $insert_arr['sign_time']   = time();
      

        $status = Db::name('activity_sign')->where('id',$sign['id'])->update($insert_arr);

        Db::name('activity')->where('id', $sign['activity_id'])->inc('total_hours', $sign['hours'])->update();

        Db::name('volunteer')->where('id', $sign['vo_id'])
            ->inc('workinghours', $sign['hours'])->update();

        Db::name('user')->where('id', $this->user_id)
            ->inc('workinghours', $sign['hours'])->update();

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('簽到成功');
    }

    /**
     * @MethodName 評論列表
     * @Author     Allen
     * @DateTime   2021-10-04T17:11:33+0800
     * @param      string
     * @return     [type]
     */
    public function getCommentList($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Activitys;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->success('請求成功');
        }

        $acmodel = new ActivityComment;

        $user_list = $acmodel
            ->alias('c')
            ->field('c.id,u.avatar,u.nickname,c.content,c.createtime')
            ->where(['c.activity_id' => $info['id'], 'c.user_id' => ['gt', 0], 'c.to_id' => 0, 'c.admin_id' => ['gt', 0]])
            ->join('user u', 'c.user_id = u.id')
            ->order('c.id desc')
            ->select();

        $admin_list = $acmodel
            ->alias('c')
            ->field('c.id,a.avatar,a.nickname,c.to_id,c.content,c.createtime')
            ->where(['activity_id' => $info['id'], 'c.to_id' => ['gt', 0], 'c.admin_id' => ['gt', 0], 'c.user_id' => 0])
            ->join('admin a', 'c.admin_id = a.id')
            ->order('c.id desc')
            ->select();

        $list = [];
        foreach ($user_list as $key => $value) {
            $arr_buf = ['avatar' => $value['avatar'], 'nickname' => $value['nickname'], 'content' => $value['content'], 'createtime' => $value['createtime'], 'son' => []];
            foreach ($admin_list as $k => $v) {
                if ($v['to_id'] == $value['id']) {
                    $arr_buf['son'] = ['avatar' => $v['avatar'], 'nickname' => $v['nickname'], 'content' => $v['content'], 'createtime' => $v['createtime']];
                }
            }
            $list[] = $arr_buf;
        }

        $this->success('請求成功', $list);
    }

    /**
     * @MethodName 報名
     * @Author     Allen
     * @DateTime   2021-10-05T14:58:19+0800
     * @param      string
     * @return     [type]
     */
    public function signup($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('signup')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Activitys;
        $info  = $model
            ->field('id,cat_id,images,title,content,max_people_num,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }
        $armodel         = new ActivityRegister;
        $register_status = $armodel
            ->where(['activity_id' => $info['id'], 'user_id' => $this->user_id])
            ->count();

        if ($register_status) {
            $this->error('請勿重複報名');
        }

        $now_signup_num = $armodel
            ->where(['activity_id' => $info['id']])
            ->count();

        if ($now_signup_num >= $info['max_people_num']) {
            $this->error('活動人數已滿');
        }

        $insert_arr                  = [];
        $insert_arr['activity_id']   = $info['id'];
        $insert_arr['cat_id']        = $info['cat_id'];
        $insert_arr['user_id']       = $this->user_id;
        $insert_arr['name']          = $rq_data['name'];
        $insert_arr['sex']           = $rq_data['sex'];
        $insert_arr['id_card']       = $rq_data['id_card'];
        $insert_arr['id_card_front'] = isset($rq_data['id_card_front']) ? $rq_data['id_card_front'] : '';
        $insert_arr['id_card_after'] = isset($rq_data['id_card_after']) ? $rq_data['id_card_after'] : '';
        $insert_arr['birthday']      = $rq_data['birthday'];
        $insert_arr['mobile']        = $rq_data['mobile'];
        $insert_arr['createtime']    = time();
        $status                      = $armodel->insert($insert_arr);

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    /**
     * @MethodName 獲取報名記錄
     * @Author     Allen
     * @DateTime   2021-10-09T18:00:11+0800
     * @param      string
     * @return     [type]
     */
    public function getSignupList($value = '')
    {
        $where = ['r.user_id' => $this->user_id];
        $model = new Activitys;
        $total = $model
            ->alias('a')
            ->join('activity_register r', 'r.activity_id = a.id')
            ->where($where)
            ->count();

        $page = new Page($total, 10);

        $list = $model
            ->alias('a')
            ->field('a.id,a.images,a.title,r.createtime')
            ->join('activity_register r', 'r.activity_id = a.id')
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('r.createtime desc')
            ->select();

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * [getlastSignupData 獲取上一次報名資料]
     * @MethodName
     * @Author     Allen
     * @DateTime   2022-07-14T21:57:06+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getlastSignupData($value = '')
    {
        $armodel = new ActivityRegister;
        $data    = $armodel
            ->field('name,sex,id_card,id_card_front,id_card_after,birthday,mobile')
            ->where(['user_id' => $this->user_id])
            ->order('id desc')
            ->find();

        $data = $data ? $data : [];
        $this->success('請求成功', $data);
    }

}
